package com.feature.core.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.feature.core.redis.FastJson2JsonRedisSerializer;

/**
 * redis配置
 * 
 */
@Configuration
public class RedisConfig  {
	@Bean
	@SuppressWarnings(value = { "unchecked", "rawtypes" })
	public BeanPostProcessor redisTemplateSerializerBeanPostProcessor(RedisConnectionFactory connectionFactory) {
		return new BeanPostProcessor() {

			@Override
			public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
				if(bean instanceof RedisTemplate) {
					RedisTemplate<Object, Object> template = (RedisTemplate)bean;
					template.setConnectionFactory(connectionFactory);

					FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

					// 使用StringRedisSerializer来序列化和反序列化redis的key值
					template.setKeySerializer(new StringRedisSerializer());
					template.setValueSerializer(serializer);

					// Hash的key也采用StringRedisSerializer的序列化方式
					template.setHashKeySerializer(new StringRedisSerializer());
					template.setHashValueSerializer(serializer);
				}
                return bean;
			}
			
		};
		
	}
}
